import MyEventEmitter from './events.js'
import {SSEStream} from '../utils/stream.mjs';

const eventEmitter = new MyEventEmitter('data')

class MyStream extends SSEStream {
    constructor() {
        super();
        // eventEmitter.listener = this.write
        eventEmitter.listener = this.#listener

        this.on('close', () => eventEmitter.closeListener(this.#listener));
    }

    #listener = data => this.write(data)
    // #listener = data => this.write(`data: ${data}\n\n`)
}

function getNewStream(){
    const stream = new SSEStream()
    const listener = data => stream.write(data)
    // eventEmitter.listener = stream.write  // 这里，不能这样用，为什么？
    eventEmitter.listener = listener

    stream.on('close', () => eventEmitter.closeListener(listener));
    return stream
}

export default class SSE {
    constructor(ctx) {
        ctx.request.socket.setTimeout(0);
        ctx.req.socket.setNoDelay(true);
        ctx.req.socket.setKeepAlive(true);

        ctx.set({
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
        });

        ctx.status = 200;
        // ctx.body = new MyStream();
        ctx.body = getNewStream();
    }
}